<template>
    <div class="wrapper">
        <el-card class="header" shadow="never">
            <Step ref="stepRef" v-bind="stepProps" />
        </el-card>
        <el-card class="from-content" :class="{ 'form-content-config': isFormConfig }" shadow="never">
            <div v-show="currentStep === 1">
                <BasicConfig ref="BasicConfigRef" class="from_basic_config__card" :group_id="0" />
            </div>
            <div v-show="currentStep === 2">
                <FormConfig ref="FormConfigRef" />
            </div>
            <div v-show="currentStep === 3">
                <OtherConfig ref="OtherConfigRef" />
            </div>
        </el-card>
        <div class="detail_footer">
            <el-button v-if="isViewDisabled" @click="goBack">返回</el-button>
            <el-button v-if="currentStep === 1 && !isViewDisabled" @click="goBack">取消</el-button>
            <el-button v-if="currentStep !== 1" @click="onPrev">上一步</el-button>
            <el-button v-if="currentStep === 2" @click="onPreview">预览</el-button>
            <el-button v-if="currentStep !== 3" type="primary" @click="onNext">下一步</el-button>
            <el-button v-if="currentStep === 3 && !isViewDisabled" type="primary" @click="onSubmit">保存</el-button>
        </div>
    </div>
    <el-drawer v-model="visible" title="预览" size="40%">
        <PreviewForm
            ref="previewFormRef"
            :activity_data="activity_data"
            :control-card-columns="controlCardColumns"
            :cover-image="coverImage"
            :submit-info="submitInfo" />
    </el-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, provide, nextTick, reactive, onBeforeMount } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useStore } from '@/store';
import { toCreateCollectionTable, showCollectTable } from '@/api/highMaterial/collectionTable';

// 组件
import Step from '@/components/Step.vue';
import PreviewForm from '../components/PreviewForm/index.vue';
import BasicConfig from './components/BasicConfig.vue';
import OtherConfig from './components/OtherConfig.vue';
import FormConfig from './components/FormConfig.vue';

const store = useStore();
const activity_data = reactive({
    form_desc: '',
    activity_name: '',
    period_type: '',
    endTime: ''
});
const router = useRouter();
const route = useRoute();
const goBack = () => {
    router.back();
};

const isViewDisabled = computed(() => {
    return route.query.type === 'view';
});

const onSubmit = async () => {
    const baseInfo = await validatorHandle[1]();
    const formData = await validatorHandle[2]();
    const otherDate = await validatorHandle[3]();

    const params = {
        id: route.query.type === 'edit' ? route.query.id : undefined,
        ...baseInfo,
        ...formData,
        ...otherDate
    };
    if (params.id) {
        const list: any = [];
        params.submit_settings.redirect.work_user_welcome.media_content?.forEach((el: any) => {
            list.push({
                media_content_id: el.media_content_id || el.material_id,
                type: el.type
            });
        });
        params.submit_settings.redirect.work_user_welcome.media_content = list;
    }
    store.dispatch('setGroupId', params.group_id);
    // 新增收集表要传公众号id
    if (route.query.official_account_id) {
        Object.assign(params, { official_account_id: route.query.official_account_id });
    }
    // 删除用来展示/赋值的日期参数 effect_date
    delete params.effect_date;
    await toCreateCollectionTable(params);
    router.push({
        path: '/content/highMaterial/collectionTable'
        // query: { group_id: params.group_id }
    });
};
/* ===================================步骤条=================================== */
const stepRef = ref();
const currentStep = ref(1);
const stepProps = {
    stepsLabel: [
        { title: '基本信息', stepIndex: 1 },
        { title: '表单配置', stepIndex: 2 },
        { title: '其他设置', stepIndex: 3 }
    ],
    totalSteps: 3
};
// 步骤条大小限制
// 下一步
const validatorHandle = {};
const doScrollToTop = () => {
    nextTick(() => {
        const main: any = document.querySelector('.el-main.main');
        main?.scrollTo(0, 0);
    });
};
const onNext = async () => {
    await validatorHandle[currentStep.value](true);
    stepRef.value.next();
    currentStep.value = stepRef.value.activeIndex;
    doScrollToTop();
};
// 上一步
const onPrev = () => {
    stepRef.value.back();
    currentStep.value = stepRef.value.activeIndex;
    doScrollToTop();
};
/* ===================================步骤条=================================== */
/* ===================================预览=================================== */
const visible = ref<boolean>(false);
const previewFormRef = ref<any>();
const controlCardColumns = reactive<Array<any>>([]);
const coverImage = ref('');
const submitInfo = reactive({});
const onPreview = async () => {
    const columns = await validatorHandle[2]();
    const configColumns = await validatorHandle[3](!['edit', 'copy', 'view'].includes(route.query.type));
    visible.value = true;
    controlCardColumns.splice(0, controlCardColumns.length, ...columns.form);
    coverImage.value = columns.cover_image;
    Object.assign(activity_data, {
        form_desc: columns.desc,
        activity_name: BasicConfigRef.value?.formData?.activity_name,
        period_type: BasicConfigRef.value?.formData?.period_type,
        endTime: BasicConfigRef.value?.formData?.effect_date?.[1]
    });
    Object.assign(submitInfo, {
        ads: configColumns?.ads,
        conclusion: configColumns?.conclusion,
        submit_settings: configColumns?.submit_settings
    });
    nextTick(() => previewFormRef.value.setState(false));
};
/* ===================================预览=================================== */

const isFormConfig = computed(() => {
    return currentStep.value === 2;
});

const BasicConfigRef = ref();
const FormConfigRef = ref();
const OtherConfigRef = ref();
// 表单配置-标题
const basicInfo = computed(() => BasicConfigRef.value?.formData);
provide('basicInfo', basicInfo);

const initDetailInfo = async () => {
    if (!['edit', 'copy', 'view'].includes(route.query.type)) return;
    const res = await showCollectTable({
        id: route.query.id
    });
    BasicConfigRef.value.setDetailInfo(res);
    FormConfigRef.value.setDetailInfo(res);
    OtherConfigRef.value.setDetailInfo(res);
};

onBeforeMount(() => {
    initDetailInfo();
});
// 查看活动
onMounted(() => {
    validatorHandle[1] = BasicConfigRef.value.getParams;
    validatorHandle[2] = FormConfigRef.value.getParams;
    validatorHandle[3] = OtherConfigRef.value.getParams;
    // const app: any = document.querySelector('.app-container')
    // app.style.height = '100%'
    const current_page = document.querySelector('.current_page');
    if (route?.query?.type == 'view' && current_page) {
        current_page.textContent = '查看收集表';
    }
});
provide('currentStep', currentStep);
</script>

<style scoped lang="scss">
.wrapper {
    padding-bottom: 68px;

    // display: grid;
    height: calc(100% - 312px);
    display: flex;
    flex-direction: column;
    grid-gap: 20px 0;

    .from-content {
        min-height: calc(100vh - 312px);
    }

    .detail_footer {
        box-sizing: border-box;
        position: absolute;
        width: calc(100% - 40px);
        bottom: 0;
        z-index: 120;

        // width: calc(100% - 335px);
        margin-right: -24px;
        height: 64px;
        padding-right: 24px;
        text-align: right;
        line-height: 64px;
        background: #fff;
        box-shadow: 0 0 10px 0 rgb(212 212 212 / 50%);
        border-radius: 2px;
    }

    .from-content {
        width: 100%;
        min-width: max-content;
    }

    .form-content-config {
        background-color: transparent;
        border: none;

        :deep(.el-card__body) {
            padding: 0;

            /* max-height: calc(100vh - 300px);
            height: calc(100vh - 300px);
            overflow-y: auto; */
        }
    }
}
</style>
